package learn_concurrent._11;

import java.util.concurrent.atomic.AtomicReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AtomicReferenceABAProblemTest {

	static AtomicReference<String> ref = new AtomicReference<>("A");
	static Logger logger = LoggerFactory.getLogger(AtomicReferenceABAProblemTest.class);

	public static void main(String[] args) throws InterruptedException {
		String prev = ref.get();

		otherThreadDoSomething();
		Thread.sleep(1000);
		boolean success = ref.compareAndSet(prev, "C");
		logger.info("change A -> C : {}", success);
	}

	static void otherThreadDoSomething() throws InterruptedException {
		new Thread(() -> logger.info("change A -> B : {}", ref.compareAndSet(ref.get(), "B")), "t1")
		.start();

		Thread.sleep(500);

		new Thread(() -> logger.info("change B -> A : {}", ref.compareAndSet(ref.get(), "A")), "t2")
		.start();
	}

}
